package com.lyn.module_custom_utils.file;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;

import com.blueberry.compress.ImageCompress;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SyncFailedException;
import java.nio.charset.StandardCharsets;

/**
 * @author:longyongning
 * @date:2021/10/2
 * @description:文件管理工具
 */
public class FileUtil {

    /**
     * 创建文件
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean createFile(String path) throws Exception {
        if (TextUtils.isEmpty(path)) return false;
        File file = new File(path);
        if (!file.exists()) {
            return file.createNewFile();
        } else {
            return true;
        }
    }

    /**
     * 创建文件夹
     *
     * @param path
     * @return
     */
    public static boolean createFolder(String path) {
        if (TextUtils.isEmpty(path)) return false;
        File file = new File(path);
        if (!file.exists()) {
            return file.mkdirs();
        } else {
            return true;
        }
    }

    /**
     * 拷贝文件到指定文件夹
     *
     * @param filePath
     * @param folderPath
     * @return
     */
    public static boolean copyFileToFolder(String filePath, String folderPath) {
        File fileDir = new File(folderPath);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String destFile = folderPath + "/" + new File(filePath).getName();
        FileInputStream streamFrom = null;
        FileOutputStream streamTo = null;
        try {
            streamFrom = new FileInputStream(filePath);
            streamTo = new FileOutputStream(destFile);
            byte buffer[] = new byte[1024];
            int len;
            while ((len = streamFrom.read(buffer)) > 0) {
                streamTo.write(buffer, 0, len);
            }
            return true;
        } catch (Exception ex) {
            return false;
        } finally {
            try {
                streamFrom.getFD().sync();
                streamFrom.close();
                streamTo.getFD().sync();
                streamTo.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件夹文件名列表
     * @param folderPath
     * @return
     */
    public static String[] getFolderFileNameList(String folderPath) {
        if (TextUtils.isEmpty(folderPath)) return null;
        File file = new File(folderPath);
        String[] list = file.list();
        return list;
    }
    /**
     * 获取文件夹文件列表
     * @param folderPath
     * @return
     */
    public static File[] getFolderFileList(String folderPath){
        if (TextUtils.isEmpty(folderPath)) return null;
        File file = new File(folderPath);
        return file.listFiles();
    }

    /**
     * 写text文本到文件
     *
     * @param text
     * @param filePath
     * @return
     */
    public static boolean writeText(String text, String filePath) {
        if (TextUtils.isEmpty(filePath)) return false;
        File file = new File(filePath);
        try {
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(text.getBytes(StandardCharsets.UTF_8));
            fileOutputStream.getFD().sync();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 读取指定文件text
     *
     * @param filePath
     * @return
     */
    public static String readText(String filePath) {
        if (TextUtils.isEmpty(filePath)) return null;
        File file = new File(filePath);
        if (!file.exists()) return null;
        if (!file.isFile()) return null;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String text = null;
            while ((text = bufferedReader.readLine()) != null) {
                stringBuffer.append(text);
            }
            fileInputStream.getFD().sync();
            fileInputStream.close();
            inputStreamReader.close();
            bufferedReader.close();
            return stringBuffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 读取指定输入流text
     *
     * @param inputStream
     * @return
     */
    public static String readText(InputStream inputStream) {
        if (inputStream == null) return null;
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String text = null;
            while ((text = bufferedReader.readLine()) != null) {
                stringBuffer.append(text);
            }
            inputStream.close();
            inputStreamReader.close();
            bufferedReader.close();
            return stringBuffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmap(String filePath) {
        if (TextUtils.isEmpty(filePath)) return null;
        File file = new File(filePath);
        if (!file.exists()) return null;
        if (!file.isFile()) return null;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
            fileInputStream.getFD().sync();
            fileInputStream.close();
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SyncFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存Bitmap
     *
     * @param bitmap
     * @param path
     * @param compressionLevel
     * @return
     */
    public static String saveBitmap(Bitmap bitmap, String path, int compressionLevel) {
        try {
            ImageCompress.nativeCompressBitmap(bitmap, compressionLevel, path, true);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @return
     */
    public static boolean deleteFile(String filePath, boolean isDeleteFolder) {
        File file = new File(filePath);
        if (!file.exists()) return false;
        if (file.isFile()) {
            return file.delete();
        }
        File[] files = file.listFiles();
        for (File item : files) {
            item.delete();
        }
        if (isDeleteFolder) {

        }
        return file.delete();
    }


    /**
     * 获取应用data路径
     *
     * @param context
     * @param folderName
     * @return
     */
    public static String getAndroidDataPath(Context context, String folderName) {
        boolean isSuccess = createFolder(context.getExternalFilesDir("").getPath().concat("/").concat(folderName).concat("/"));
        if (isSuccess) {
            return context.getExternalFilesDir("").getPath().concat("/").concat(folderName).concat("/");
        }
        return null;
    }

    /**
     * 获取储存根目录路径
     *
     * @return
     */
    public static String getTheRootDirectory() {
        return Environment.getExternalStorageDirectory().getPath().concat("/");
    }

}
